<template>
  <div class="app-container">
    <div
      class="app-container-wrap"
      v-show="!modifyInfo.visible && !detailInfo.visible"
    >
      <div class="app-container-flex">
        <div class="left-container">
          <div class="left-container-title">货架信息</div>
          <div class="left-container-header">
            <el-input
              v-model="treeFilter.query.keyword"
              style="width: 200px; margin-right: 10px"
              :clearable="true"
              placeholder="仓库名称/货架编号"
              @keyup.enter="getTree('')"
            ></el-input>
            <el-button :plain="true" @click="getTree('')">搜索</el-button>
          </div>
          <div class="left-container-header">
            <el-button
              v-if="$permission('cargoSpace:addShelfNumber')"
              :plain="true"
              :disabled="
                !treeInfo.node ||
                (treeInfo.node.parentId && treeInfo.node.parentId !== -1)
              "
              @click="addShelfNumber"
              >新增
            </el-button>
            <el-button
              v-if="$permission('cargoSpace:updateShelfNumber')"
              :plain="true"
              :disabled="
                !treeInfo.node ||
                (treeInfo.node.parentId &&
                  (treeInfo.node.parentId === -1 || tableInfo.data.length > 0))
              "
              @click="updateShelfNumber"
              >修改</el-button
            >
            <el-button
              v-if="$permission('cargoSpace:removeShelfNumber')"
              :plain="true"
              :disabled="
                !treeInfo.node ||
                (treeInfo.node.parentId &&
                  (treeInfo.node.parentId === -1 || tableInfo.data.length > 0))
              "
              @click="removeShelfNumber"
              >删除</el-button
            >
          </div>
          <div class="left-container-main main-flex">
            <el-tree
              ref="shelfNumTree"
              :data="treeInfo.data"
              highlight-current
              :props="treeInfo.defaultProps"
              :default-expanded-keys="treeInfo.treeData"
              node-key="resourceCode"
              :default-checked-keys="[treeInfo.checked]"
              :default-expand-all="false"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            />
          </div>
        </div>
        <div class="right-container">
          <div class="right-container-title">货位信息</div>
          <div class="layui-card-body layui-card-body-height">
            <div class="filter-wrapper">
              <new-page-filter
                v-model:query="filterInfo.query.queryMap"
                :query-more-json="true"
                :filter-list="filterInfo.searchList"
                :filter-btn="filterInfo.searchBtn"
                :clear-type="clearType"
                :slip-select-request="slipSelectRequest"
              >
              </new-page-filter>
            </div>
            <div class="filter-wrapper">
              <new-page-filter :filter-btn="filterInfo.btnList">
                <template v-slot:filter-addShelfNo>
                  <el-button
                    @click="addShelfNo"
                    :disabled="
                      !treeInfo.node ||
                      (treeInfo.node.parentId && treeInfo.node.parentId === -1)
                    "
                    >新增</el-button
                  >
                </template>
                <template v-slot:filter-removeShelfNo>
                  <el-button
                    @click="removeShelfNo"
                    :disabled="!canRemoveShelfNo"
                    >删除</el-button
                  >
                </template>
                <template v-slot:filter-uploadOut>
                  <el-button :plain="true" @click="downloadTemplate"
                    >下载模板</el-button
                  >
                </template>
                <template v-slot:filter-uploadIn>
                  <el-upload
                    :headers="uploadInfo.headers"
                    :show-file-list="false"
                    :on-error="uploadError"
                    :on-success="importProduct"
                    :before-upload="beforeProductUpload"
                    :action="uploadInfo.action"
                  >
                    <el-button>导入模板</el-button>
                  </el-upload>
                </template>
                <template v-slot:filter-quickAdd>
                  <el-button
                    @click="quickAdd"
                    :disabled="
                      !(
                        treeInfo.node.parentId &&
                        treeInfo.node.parentId !== -1 &&
                        tableInfo.data.length === 0
                      )
                    "
                    >快捷创建
                  </el-button>
                </template>
                <template v-slot:filter-setRules>
                  <el-button
                    @click="setRules"
                    :disabled="!tableInfo.selections.length"
                    >设置上架规则</el-button
                  >
                </template>
                <template v-slot:filter-bindProduct>
                  <el-button
                    @click="bindProduct"
                    :disabled="!tableInfo.selections.length"
                    >绑定产品</el-button
                  >
                </template>
                <template v-slot:filter-printShelfNumber>
                  <el-button
                    @click="printShelfNumber"
                    :disabled="!tableInfo.selections.length"
                    >打印货位编号</el-button
                  >
                </template>
              </new-page-filter>
              <div class="display-flex">
                <el-button @click="preferenceInfo.visible = true"
                  >偏好设置</el-button
                >
              </div>
            </div>
            <table-container
              :refresh="tableInfo.refresh"
              :init-curpage="tableInfo.initCurpage"
              v-model:data="tableInfo.data"
              :api="tableInfo.api"
              v-model:query="filterInfo.query"
              :field-list="tableInfo.fieldList"
              :handle="tableInfo.handle"
              :row-class-name="tableRowClassName"
              @sortChange="sortChange"
              @handleEvent="handleEvent"
            >
              <template v-slot:col-locationNo="scope">
                <span
                  v-if="$permission('cargoSpace:detail')"
                  class="slip-edit"
                  @click="showDetail(scope.row)"
                  >{{ scope.row.locationNo }}</span
                >
                <span v-else class="slip-edit">{{ scope.row.locationNo }}</span>
              </template>
            </table-container>
          </div>
        </div>
      </div>
    </div>
    <chose-printer
      :visible="printerInfo.visible"
      @callBack="handlePrinterCallBack"
    />

    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <modify
      v-if="modifyInfo.visible"
      :orderId="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :modifyType="modifyInfo.type"
      :params="modifyInfo.params"
      @returnModify="returnModify"
    />
    <detail
      v-if="detailInfo.visible"
      :orderId="detailInfo.id"
      v-model:visible="detailInfo.visible"
      @returnBack="getList"
    />
    <!-- 新增修改货架弹窗 -->
    <page-dialog
      v-if="shelfNumberInfo.visible"
      :title="shelfNumberInfo.title"
      v-model:visible="shelfNumberInfo.visible"
      :width="shelfNumberInfo.width"
      :bt-loading="shelfNumberInfo.btLoading"
      :bt-list="shelfNumberInfo.btList"
      @reset="closeShelfNumber"
    >
      <!-- form -->
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="shelfNumberFormInfo.ref"
        :data="shelfNumberFormInfo.data"
        :field-list="shelfNumberFormInfo.fieldList"
        :rules="shelfNumberFormInfo.rules"
        :label-width="shelfNumberFormInfo.labelWidth"
      >
      </page-form>
    </page-dialog>
    <!-- 上架规则弹窗 -->
    <page-dialog
      v-if="rulesInfo.visible"
      :title="rulesInfo.title"
      v-model:visible="rulesInfo.visible"
      :width="rulesInfo.width"
      :bt-loading="rulesInfo.btLoading"
      :bt-list="rulesInfo.btList"
      @reset="closeRules"
    >
      <!-- form -->
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="rulesFormInfo.ref"
        :data="rulesFormInfo.data"
        :field-list="rulesFormInfo.fieldList"
        :rules="rulesFormInfo.rules"
        :label-width="rulesFormInfo.labelWidth"
        @handleEvent="ruleFormHandleEvent"
      >
      </page-form>
    </page-dialog>
    <select-product
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      v-model:query="productInfo.query"
      :isShowRightTable="true"
      @callback="selectProductBack"
    />
  </div>
</template>

<script setup name="cargoSpaceManage">
import {
  getGoodsLocationcustomizeListAll,
  goodsLocationSetPutawayRule,
  deleteGoodsLocation,
  goodsLocationEnable,
  goodsLocationDisable,
  goodsLocationBindProduct,
  shelfNoPrint,
  getGoodsShelfTree,
  createGoodsShelf,
  updataGoodsShelf,
  removeGoodsShelf,
} from '@/api/wms.js'
import { getDepotAll } from '@/api/core.js'
import { exportTemplateExcel } from '@/api/pub'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { ElLoading } from 'element-plus'
import SelectProduct from './selectProduct'
import axios from 'axios'
import Modify from './modify'
import Detail from './detail'

const { proxy } = getCurrentInstance()

// 过滤相关配置
const treeFilter = ref({
  query: {
    keyword: '',
  },
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      depotAuth: {
        asTbName: 'wms_goods_location',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
      depotId: {
        queryType: 'IN',
        value: '',
      },
      shelfId: {
        //货架id
        queryType: 'IN',
        value: '',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      label: '新增',
      value: 'addShelfNo',
      show: proxy.$permission('cargoSpace:addShelfNo'),
    },
    {
      type: 'slot',
      value: 'removeShelfNo',
      show: proxy.$permission('cargoSpace:removeShelfNo'),
    },
    {
      type: 'slot',
      value: 'uploadOut',
      show: proxy.$permission('cargoSpace:uploadOut'),
    },
    {
      type: 'slot',
      value: 'uploadIn',
      show: proxy.$permission('cargoSpace:uploadIn'),
    },
    {
      type: 'slot',
      value: 'quickAdd',
      show: proxy.$permission('cargoSpace:quickAdd'),
    },
    {
      type: 'slot',
      value: 'setRules',
      show: proxy.$permission('cargoSpace:setRules'),
    },
    {
      type: 'slot',
      value: 'bindProduct',
      show: proxy.$permission('cargoSpace:bindProduct'),
    },
    {
      type: 'slot',
      value: 'printShelfNumber',
      show: proxy.$permission('cargoSpace:printShelfNumber'),
    },
  ],
})
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/wms/goodsLocation/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
// 权限树
const treeInfo = ref({
  data: [],
  nodeKey: 'code',
  checked: [],
  treeData: [],
  node: {},
  defaultProps: {
    children: 'children',
    label: function (data, node) {
      if (data.code) {
        return data.name + '/' + data.code
      } else {
        return data.name
      }
    },
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [{ label: '货位编号', value: 'locationNo', type: 'slot' }],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('cargoSpace:update'),
      },

      {
        label: '复制',
        event: copyShelfNo,
        show: proxy.$permission('cargoSpace:copyShelfNo'),
      },
      {
        label: '启用',
        event: enable,
        show: proxy.$permission('cargoSpace:enabled'),
        ifRender: function (row) {
          return row.status === 0
        },
      },
      {
        label: '停用',
        event: disabled,
        show: proxy.$permission('cargoSpace:disabled'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '删除',
        event: removeShelfNo,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('cargoSpace:removeShelfNo'),
      },
    ],
  },
})
// 弹窗相关
const shelfNumberInfo = ref({
  title: '',
  visible: false,
  type: '',
  width: '700px',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: closeShelfNumber, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveShelfNumber,
      saveLoading: false,
      show: true,
    },
  ],
})
// 表单相关
const shelfNumberFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '仓库名称',
      value: 'depotName',
      type: 'input',
      disabled: true,
    },
    {
      label: '仓库编码',
      value: 'depotCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '货架序号',
      value: 'shelfSerialNo', //name
      type: 'input',
    },
    {
      label: '货架编号',
      value: 'shelfNumber', //code
      type: 'input',
    },
  ],
  rules: {
    shelfSerialNo: [
      { required: true, message: '请输入货架序号', trigger: 'blur' },
      { validator: proxy.$validate.naturalnumber, trigger: 'blur' },
    ],
    shelfNumber: [
      { required: true, message: '请输入货架编号', trigger: 'blur' },
    ],
  },
  labelWidth: '130px',
})
// 弹窗相关
const rulesInfo = ref({
  title: '设置上架规则',
  visible: false,
  type: '',
  width: '700px',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: closeRules, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveRules,
      saveLoading: false,
      show: true,
    },
  ],
})
// 表单相关
const rulesFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '寄售产品允许混放',
      value: 'isConsignProductMixing',
      type: 'select-model',
      event: 'isConsignProductMixing',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '寄售同产品不同批号效期允许混放',
      value: 'isConsignBatchExpiryDateMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '寄售同产品不同供应商允许混放',
      value: 'isConsignSupplierMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '非寄售产品允许混放',
      value: 'isNotConsignProductMixing',
      event: 'isNotConsignProductMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '非寄售同产品不同批号效期允许混放',
      value: 'isNotConsignBatchExpiryDateMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '非寄售同产品不同供应商允许混放',
      value: 'isNotConsignSupplierMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
  ],
  rules: {},
  labelWidth: '140px',
})
const productInfo = ref({
  visible: false,
  query: {},
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const modifyInfo = ref({
  visible: false,
  id: '',
  title: '',
  type: '', //1,正常新增修改，2快捷创建，3复制行创建
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const canRemoveShelfNo = computed(() => {
  return tableInfo.value.selections.length
})
setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'enabled_type',
      show: false,
      hidden: true,
    },
    depotName: {
      label: '仓库',
      value: 'depotName',
      asValue: 'depotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '1',
        isCargoSpaceManage: 1,
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
    locationNo: {
      label: '货位编号',
      value: 'locationNo',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    locationTypeValue: {
      label: '货位属性',
      value: 'locationTypeValue',
      asValue: 'locationType',
      componentType: 'select-model',
      code: 'goods_location_type',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getTree()
}
//获取货架信息
function getTree(parentId = '', shelfId = '') {
  let params = {
    keyword: treeFilter.value.query.keyword,
  }
  getGoodsShelfTree(params).then((res) => {
    if (res && res.success) {
      if (res.data && res.data.length) {
        let data = {}
        if (parentId) {
          let newData = res.data.find((item) => parentId === item.id)
          if (shelfId && newData.children && newData.children.length) {
            data = newData.children.find((item) => shelfId === item.id)
          } else {
            data = newData
          }
        } else {
          data = res.data[0]
        }
        treeInfo.value.node = data
        shelfNumberFormInfo.value.data.depotName = data.name
        shelfNumberFormInfo.value.data.depotCode = data.code
        shelfNumberFormInfo.value.data.depotId = data.id
        filterInfo.value.query.queryMap.depotId.value = data.id
        filterInfo.value.query.queryMap.shelfId.value = ''
        proxy.$nextTick(() => {
          proxy.$refs.shelfNumTree.setCurrentKey(data.resourceCode)
        })
      }
      treeInfo.value.data = res.data
      getCustomize()
    }
  })
}
function handleNodeClick(node) {
  treeInfo.value.node = node
  if (node.parentId === -1) {
    shelfNumberFormInfo.value.data = {}
    shelfNumberFormInfo.value.data.depotName = node.name
    shelfNumberFormInfo.value.data.depotCode = node.code
    shelfNumberFormInfo.value.data.depotId = node.id
    filterInfo.value.query.queryMap.depotId.value = node.id
    filterInfo.value.query.queryMap.shelfId.value = ''
    shelfNumberFormInfo.value.data.shelfSerialNo = ''
    shelfNumberFormInfo.value.data.shelfNumber = ''
    treeInfo.value.parentData = {}
    getList()
  } else {
    let parentData = treeInfo.value.data.find(
      (item) => item.id === node.parentId
    )
    treeInfo.value.parentData = parentData
    shelfNumberFormInfo.value.data = node
    shelfNumberFormInfo.value.data.depotName = parentData.name
    shelfNumberFormInfo.value.data.depotCode = parentData.code
    shelfNumberFormInfo.value.data.depotId = parentData.id
    shelfNumberFormInfo.value.data.shelfSerialNo = node.name
    shelfNumberFormInfo.value.data.shelfNumber = node.code
    treeInfo.value.node.shelfSerialNo = node.name
    treeInfo.value.node.shelfNumber = node.code
    filterInfo.value.query.queryMap.depotId.value = parentData.id
    filterInfo.value.query.queryMap.shelfId.value = node.id
    getList()
  }
}
//新增货架
function addShelfNumber() {
  shelfNumberInfo.value.title = '新增货架'
  shelfNumberInfo.value.visible = true
}
//修改货架
function updateShelfNumber() {
  shelfNumberInfo.value.title = '修改货架'
  let node = treeInfo.value.node
  let parentData = treeInfo.value.parentData
  shelfNumberFormInfo.value.data = node
  shelfNumberFormInfo.value.data.depotName = parentData.name
  shelfNumberFormInfo.value.data.depotCode = parentData.code
  shelfNumberFormInfo.value.data.depotId = parentData.id
  shelfNumberFormInfo.value.data.shelfSerialNo = node.name
  shelfNumberFormInfo.value.data.shelfNumber = node.code
  shelfNumberInfo.value.visible = true
}
//删除货架
function removeShelfNumber() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let ids = [treeInfo.value.node.id]
      removeGoodsShelf(ids).then((res) => {
        if (res && res.success) {
          let parentId = ''
          if (treeInfo.value.node.parentId === -1) {
            parentId = treeInfo.value.node.id
          } else {
            parentId = treeInfo.value.node.parentId
          }
          getTree(parentId)
        }
      })
    })
}
//货架保存
function saveShelfNumber() {
  shelfNumberFormInfo.value.ref.validate((valid) => {
    if (valid) {
      let api =
        treeInfo.value.node.parentId === -1
          ? createGoodsShelf
          : updataGoodsShelf
      api(shelfNumberFormInfo.value.data).then((res) => {
        if (res && res.success) {
          let parentId = ''
          let shelfId = ''
          if (treeInfo.value.node.parentId === -1) {
            parentId = treeInfo.value.node.id
          } else {
            parentId = treeInfo.value.node.parentId
            shelfId = treeInfo.value.node.id
          }
          getTree(parentId, shelfId)
          closeShelfNumber()
        }
      })
    }
  })
}
//货架关闭
function closeShelfNumber() {
  shelfNumberInfo.value.visible = false
  shelfNumberFormInfo.value.data = {}
}
//设置上架规则
function setRules() {
  rulesFormInfo.value.data = {
    isConsignProductMixing:
      proxy.$store.state.permission.systemConfig.is_consign_product_mixing,
    isConsignBatchExpiryDateMixing:
      proxy.$store.state.permission.systemConfig
        .is_consign_batch_expiry_date_mixing,
    isConsignSupplierMixing:
      proxy.$store.state.permission.systemConfig.is_consign_supplier_mixing,
    isNotConsignProductMixing:
      proxy.$store.state.permission.systemConfig.is_not_consign_product_mixing,
    isNotConsignBatchExpiryDateMixing:
      proxy.$store.state.permission.systemConfig
        .is_not_consign_batch_expiry_date_mixing,
    isNotConsignSupplierMixing:
      proxy.$store.state.permission.systemConfig.is_not_consign_supplier_mixing,
    status: 1,
  }
  ruleFormHandleEvent(
    'isConsignProductMixing',
    rulesFormInfo.value.data.isConsignProductMixing
  )
  ruleFormHandleEvent(
    'isNotConsignProductMixing',
    rulesFormInfo.value.data.isNotConsignProductMixing
  )
  rulesInfo.value.visible = true
}
//关闭规则弹窗
function closeRules() {
  rulesInfo.value.visible = false
  rulesFormInfo.value.data = {}
}
//保存规则
function saveRules() {
  let ids = getIds(undefined)
  let params = {
    ...rulesFormInfo.value.data,
    ids: ids,
  }
  goodsLocationSetPutawayRule(params).then((res) => {
    if (res && res.success) {
      getList()
      closeRules()
    }
  })
}
//规则设置
function ruleFormHandleEvent(str, val) {
  if (str === 'isConsignProductMixing') {
    if (val == 1) {
      rulesFormInfo.value.data.isConsignBatchExpiryDateMixing = '-2'
      rulesFormInfo.value.data.isConsignSupplierMixing = '-2'
      showRuleFieldListListItem(false, 'isConsignBatchExpiryDateMixing')
      showRuleFieldListListItem(false, 'isConsignSupplierMixing')
    } else {
      if (rulesFormInfo.value.data.isConsignBatchExpiryDateMixing === '-2') {
        rulesFormInfo.value.data.isConsignBatchExpiryDateMixing = '0'
      }
      if (rulesFormInfo.value.data.isConsignSupplierMixing === '-2') {
        rulesFormInfo.value.data.isConsignSupplierMixing = '0'
      }
      showRuleFieldListListItem(true, 'isConsignBatchExpiryDateMixing')
      showRuleFieldListListItem(true, 'isConsignSupplierMixing')
    }
  } else if (str === 'isNotConsignProductMixing') {
    if (val == 1) {
      rulesFormInfo.value.data.isNotConsignBatchExpiryDateMixing = '-2'
      rulesFormInfo.value.data.isNotConsignSupplierMixing = '-2'
      showRuleFieldListListItem(false, 'isNotConsignBatchExpiryDateMixing')
      showRuleFieldListListItem(false, 'isNotConsignSupplierMixing')
    } else {
      if (rulesFormInfo.value.data.isNotConsignBatchExpiryDateMixing === '-2') {
        rulesFormInfo.value.data.isNotConsignBatchExpiryDateMixing = '0'
      }
      if (rulesFormInfo.value.data.isNotConsignSupplierMixing === '-2') {
        rulesFormInfo.value.data.isNotConsignSupplierMixing = '0'
      }
      showRuleFieldListListItem(true, 'isNotConsignBatchExpiryDateMixing')
      showRuleFieldListListItem(true, 'isNotConsignSupplierMixing')
    }
  }
}
function showRuleFieldListListItem(show, nameValue) {
  rulesFormInfo.value.fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
//快捷创建
function quickAdd() {
  modifyInfo.value.id = ''
  modifyInfo.value.title = '快捷创建货位'
  modifyInfo.value.type = '2'
  modifyInfo.value.params = {
    depotName: treeInfo.value.parentData.name,
    depotId: treeInfo.value.parentData.id,
    depotCode: treeInfo.value.parentData.code,
    shelfNumber: treeInfo.value.node.shelfNumber,
    shelfId: treeInfo.value.node.id,
    shelfSerialNo: treeInfo.value.node.shelfSerialNo,
  }
  modifyInfo.value.visible = true
}
//复制货位
function copyShelfNo(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.id = row.id
  modifyInfo.value.title = '复制货位'
  modifyInfo.value.params = {}
  modifyInfo.value.type = '3'
  modifyInfo.value.visible = true
}
//创建
function addShelfNo() {
  modifyInfo.value.id = ''
  modifyInfo.value.title = '新增货位'
  modifyInfo.value.type = '1'
  modifyInfo.value.params = {
    depotName: treeInfo.value.parentData.name,
    depotId: treeInfo.value.parentData.id,
    depotCode: treeInfo.value.parentData.code,
    shelfNumber: treeInfo.value.node.shelfNumber,
    shelfId: treeInfo.value.node.id,
    shelfSerialNo: treeInfo.value.node.shelfSerialNo,
  }
  modifyInfo.value.visible = true
}
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.id = row.id
  modifyInfo.value.title = '修改货位'
  modifyInfo.value.params = {}
  modifyInfo.value.type = '1'
  modifyInfo.value.visible = true
}
//绑定产品
function bindProduct() {
  productInfo.value.visible = true
}
//选择产品返回
function selectProductBack(data) {
  if (data && data.length) {
    let params = {
      ids: getIds(),
      wmsGoodsLocationProductRelationVOList: data.map((item) => {
        return {
          goodsLocationId: '',
          capacity: item.capacity,
          productId: item.productId,
        }
      }),
    }
    goodsLocationBindProduct(params).then((res) => {
      if (res && res.success) {
        getList()
      }
    })
  }
}
//启用
function enable(row) {
  const ids = getIds(row)
  goodsLocationEnable(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
//停用
function disabled(row) {
  const ids = getIds(row)
  goodsLocationDisable(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
//打印货架编号
function printShelfNumber(row) {
  let data = []
  if (row && row.id) {
    data.push(row.id)
  } else {
    data = tableInfo.value.selections.map((item) => item.id)
  }
  if (data.length) {
    shelfNoPrint(data).then((res) => {
      if (res && res.success) {
        printerInfo.value.visible = true
        printerInfo.value.data = res.data
      }
    })
  } else {
    proxy.$message({
      message: '选择需要打印的二维码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
  }
}
function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function getIds(row = undefined) {
  if (row && row.id) {
    return [row.id]
  } else {
    return tableInfo.value.selections.map((value) => value.id)
  }
}
function returnModify() {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  _filterInfo.query.queryMap = {}
  _filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//删除
function removeShelfNo(row) {
  let ids = getIds(row)
  if (row && row.id) {
    deleteGoodsLocation(ids).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        deleteGoodsLocation(ids).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      })
  }
}

//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    console.log(row.id, 'row.id')
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey:
      'wmsGoodsLocationList-com.slip.spd.entity.vo.wms.WmsGoodsLocationVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getGoodsLocationcustomizeListAll
      if (treeInfo.value.data.length > 0) {
        getList()
      }
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error('系统错误')
  }
  uploadInfo.value.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getTree()
    getList()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 0,
      showClose: true,
    })
  }
}
function downloadTemplate() {
  exportTemplateExcel('wms_goods_location_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
</script>

<style scoped lang="scss">
.app-container {
  height: calc(100vh - 68px);
}
.app-container-wrap {
  height: 100% !important;
}
.left-container {
  min-width: 350px;
  .left-container-header {
    display: flex;
    padding: 0 0 7px 0 !important;
  }

  .border-style-bottom {
    margin-bottom: 0;
  }
}
.main-flex {
  flex-grow: 1;
  display: flex;
  flex-wrap: nowrap;
  height: calc(100% - 105px);
  .el-tree {
    width: 100%;
    padding-bottom: 20px;
    overflow-y: auto;
  }
}
</style>
